import datetime
import os


class FileUtils:
    def __init__(self, path):
        self.path = path

    # 判空填充文件路径
    def fix_file_path(self):
        isExists = os.path.exists(self.path)
        if not isExists:
            os.mkdir(self.path)

    # 读取规则文件
    def read_rule(self):
        with open(self.path, 'r', encoding='utf-8') as f:
            r_rule = f.readline().split()
        f.close()
        return r_rule

    # 合并文件夹文件
    def text_file_merger(self, file_name):
        file_lists = []
        entry_lists = os.scandir(self.path)
        for entry_list in entry_lists:
            if entry_list.is_file():
                file_lists.append(entry_list.path)
        # 新的文件名中以日期结尾，以下获取系统日期
        date = str(datetime.datetime.today())[0:10]
        for file in file_lists:
            file_type_extension = os.path.splitext(file)[1]  # 获取文件的扩展名
            joined_file_name = file_name + '{}{}'.format(date, file_type_extension)
            with open(file, 'rb') as file_to_read:
                file_contents = file_to_read.read()
                with open(self.path + os.sep + joined_file_name, 'ab+') as file_to_write:
                    file_to_write.write(file_contents)

    @staticmethod
    def find_rule_file():
        # 读取配置文件
        read_path = os.getcwd() + os.sep + "make_data" + os.sep + "data" + os.sep + "testDataRule" + os.sep
        print(read_path)
        rule_file_name = ""
        flag = 1
        while flag == 1:
            rule_file_name = input("请输入规则文件名：")
            rule_file_isExists = os.path.exists(read_path + rule_file_name)
            if rule_file_isExists:
                break
            else:
                print("文件不存在，请确认testDataRule文件夹下存在目标文件！")
        return read_path, rule_file_name

    @staticmethod
    def create_rule_file(data_rule):
        # 保存规则文件
        is_create_rule = input("请选择是否生成规则文件：y/n ? ")
        if is_create_rule == 'y':
            rule_file_name = input("请输入您要保存的规则文件名，如果重复会覆盖请谨慎选择: ")
            print(rule_file_name)
            rule_path = os.getcwd() + os.sep + "make_data" + os.sep + "data" + os.sep + "testDataRule"
            FileUtils(rule_path).fix_file_path()
            rule_file_path = rule_path + os.sep + rule_file_name
            # 指定文件编码
            fw_rule = open(rule_file_path, 'w', encoding='utf-8')
            fw_rule.write(data_rule)
            fw_rule.close()
